<?php
/**
 * 微信红包接口封装类
 *
 * @author liang<lang@vip.deyi.com>
 * @since   2016/4/25 15:36
 * @copyright  deyi.com
 */


namespace Deyi\Weixin;

/**
 * Class HongBaoHelper
 * @package Deyi\Weixin
 */
class HongBaoHelper
{
    /**
     * 参数加密key
     * @var
     */
    private $key;

    /**
     *  获取CURL SSL配置信息
     *
     * @author liang<lang@vip.deyi.com>
     * @return array
     */
    public function getSSLConfig()
    {
        return [
            CURLOPT_SSLCERT => dirname(__FILE__) . '/hongbao/apiclient_cert.pem',
            CURLOPT_SSLKEY => dirname(__FILE__) . '/hongbao/apiclient_key.pem',
            CURLOPT_CAINFO => dirname(__FILE__) . '/hongbao/rootca.pem'
        ];
    }

    /**
     * @param mixed $key
     */
    public function setKey($key)
    {
        $this->key = $key;
    }

    /**
     *  生成提交的xml文件
     *
     * @author liang<lang@vip.deyi.com>
     * @param $arr
     * @return string
     */
    public function generateXml($arr)
    {
        $xml = "<xml>\n";

        $arr['sign'] = $this->getSign($arr);

        foreach ($arr as $k => $v) {
            $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . ">\n";
        }

        $xml .= '</xml>';

        return $xml;
    }

    /**
     *  生成签名
     *
     * @author liang<lang@vip.deyi.com>
     * @param $arr
     * @return mixed
     */
    private function getSign($arr)
    {
        ksort($arr);

        $arr['key'] = $this->key;

        $query = [];

        foreach ($arr as $k => $v) {
            $query[] = $k . '=' . $v;
        }

        return strtoupper(md5(implode('&', $query)));
    }
}
